package com.ruoyi.cmdb.util;

import com.ruoyi.cmdb.vo.PortInfo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class Port {
    public void run(String... args) throws Exception {
        int START_PORT = 1;
        int END_PORT = 65535;
        String TARGET_IP = "192.168.32.144"; // 替换为你要扫描的IP地址
        int TIMEOUT = 200; // 设置连接超时时间（毫秒）
        System.out.println("Scanning ports on IP: " + TARGET_IP);
        for (int port = START_PORT; port <= END_PORT; port++) {
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress(TARGET_IP, port), TIMEOUT);
                System.out.println("Port " + port + " is open");
            } catch (SocketTimeoutException e) {
                // Port is closed or not responding in time
            } catch (IOException e) {
                // Some other IOException occurred while connecting
            }
        }
    }

    public List<PortInfo> scanPortByIp(String ip){
        List<PortInfo> portList=new ArrayList<>();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("nmap", "-sV", "-O", ip);
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if(line.contains("tcp")){
                    //System.out.println(line);
                    String portNumber=line.split("/")[0];
                    line=line.replaceAll(" +"," ");
                    String type=line.split(" ")[2];
                    //System.out.println(port);
                    //System.out.println(type);
                    PortInfo portInfo=new PortInfo(Integer.parseInt(portNumber),type);
                    portList.add(portInfo);
                }
            }

            int exitCode = process.waitFor();
            //System.out.println("\nExited with error code : " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return portList;
    }
}
